package com.frontop.terminal.timer;

import cn.hutool.core.io.IORuntimeException;
import cn.hutool.http.ContentType;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.frontop.terminal.constant.InterfaceConst;
import com.frontop.terminal.entity.Terminal;
import com.frontop.terminal.entity.TerminalConfig;
import com.frontop.terminal.enums.HeaderEnum;
import com.frontop.terminal.util.ReadDataUtil;
import com.frontop.terminal.util.SystemMonitoringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Objects;

/**
 * <p>
 * 心跳
 * </P>
 *
 * @author :CCC
 * @since :2021-05-17 17:22:00
 **/
@SuppressWarnings("ConstantConditions")
@Component
@Slf4j
public class HeartbeatTimer {

    public HeartbeatTimer() throws IOException {
        this.service();
    }

    @Autowired
    Environment environment;

    @Scheduled(cron = "*/15 * * * * ?")
    public void service() throws IOException {
        Terminal terminal = SystemMonitoringUtil.getTerminal();
        TerminalConfig terminalConfig = ReadDataUtil.getTerminalConfig();
        if (Objects.isNull(terminalConfig)) {
            return;
        }


        try {
            terminal.setAlias(Objects.requireNonNull(terminalConfig).getAlias());
            terminal.setTerminalVersion(terminalConfig.getVersion());
            terminal.setPort(Integer.valueOf(environment.getProperty("local.server.port")));
            String json = JSON.toJSONString(terminal);

            //获取服务器配置地址拼装完整接口
            String url = terminalConfig.getServerAddress() + InterfaceConst.SEND_HEARTBEAT;
            HttpRequest.post(url)
                    .header(HeaderEnum.AUTH_TYPE.getKey(), HeaderEnum.AUTH_TYPE.getValue())
                    .header(HeaderEnum.TERMINAL_TOKEN.getKey(), terminalConfig.getAuthorizationCode())
                    .contentType(ContentType.JSON.getValue())
                    .body(json)
                    .executeAsync();
        } catch (IORuntimeException e) {
            log.error(terminalConfig.getIp() + " 服务器未上线");
        } catch (IllegalArgumentException e) {
            log.error("配置文件未配置或未正确配置");
        } catch (NullPointerException e) {
            log.error("[TerminalConfig.json]配置文件可能不存在,终止运行");
            e.printStackTrace();
            System.exit(-1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
